#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

static void serveFile(int fd, const char* filename)
{
    FILE *resource = NULL;

    resource = fopen(filename, "r");
    if (resource != NULL) {
        int out_fd = fileno(resource);
        int result;
        for (;;) {
            result = sendfile(fd, out_fd, NULL, 512);
            if (result < 0)
                break;
        }
    }
    fclose(resource);
}

int main(int argc, char *argv[])
{
    int sockfd;
    int len;
    struct sockaddr_in address;
    int result;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr("127.0.0.1");
    address.sin_port = htons(27788);
    len = sizeof(address);
    result = connect(sockfd, (struct sockaddr *)&address, len);

    if (result == -1)
    {
        perror("oops: client1");
        return 1;
    }

    char buf[1024];
    sprintf(buf, "POST /abc/test.zip HTTP/1.1\r\n");
    write(sockfd, buf, strlen(buf));

    sprintf(buf, "Project: test\r\n");
    write(sockfd, buf, strlen(buf));

    sprintf(buf, "Auth: test\r\n");
    write(sockfd, buf, strlen(buf));

    const char *filename = "/root/Python-3.4.3.tgz";

    struct stat st;
    stat(filename, &st);
    sprintf(buf, "Content-Length: %d\r\n\r\n", st.st_size);
    write(sockfd, buf, strlen(buf));

    serveFile(sockfd, filename);

    while (read(sockfd, buf, 1024) > 0)
        printf(buf);

    close(sockfd);

    return 0;
}
